import { loginByUsername, sysToken, logout, getUserInfo, sysLogin } from '@/api/login'
// loginByUsername
import { getToken, getPath, setToken, setName, setPath, setVersion, removePath, removeVersion, removeIndependent, removeName,
   removeAvatar, removeIs_Jurisdiction, removeToken,removeAgent} from '@/utils/auth'
// import { getToken as loginToken } from '@/api/article'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'
const user = {
  state: {
    user: Cookies.get('_WeliamAdminName') || 'admin',
    status: '',
    usersAvatar: `${require('@/assets/store/default_avatar.png')}`,
    code: '',
    token: getToken(),
    avatar: Cookies.get('_WeliamAdminLogo'),
    introduction: '',
    routerPath: getPath() || {},
    roles: [],
    // 默认获取cookie平台的类型
    rolesDefult: [Cookies.get('VERSION')] || ['user'],
    setting: {
      articlePlatform: []
    },
    h_aid:''
  },
  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
      console.log(state.token)
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.user = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      console.log('SET_ROLES', roles)
      state.roles = roles
    },
    SET_ROUTER_PATH(state, roles) {
      console.log("较好的水电费",state,roles)
      state.routerPath = roles
    },
    SET_ROLES_DEFULT(state, defult) {
      state.rolesDefult = defult
    },
    H_AID(state,h_aid){
      console.log("====================方法大幅度:",state,h_aid)
      state.h_aid = h_aid
    }
  },
  actions: {
    qrcodeLogin({ commit }, qrcodeData) {
      return new Promise((resolve, reject) => {
        sysLogin({ qrcodeData: qrcodeData }).then(response => {
          if (response.data.code === 1) {
            const userData = response.data.data || {}
            // is_super判断是否为超级用户，location确定为版本还是用户
            const { jurisdiction, is_super, location } = userData
            console.log("待发货第三方的",response.data.data)
            // 修改vuex里的rolesDefult是版本还是用户
            commit('SET_ROLES_DEFULT', [location])
            commit('SET_VERSION', location)
            // 直接设为置cookie版本还是用户
            setVersion(location)
            commit('SET_ROUTER_PATH', { jurisdiction, is_super: is_super === 0 ? 0 : 1 })
            setPath({ jurisdiction, is_super })
            commit('SET_TOKEN', true)
            setName(userData.nickname)
            commit('SET_NAME', userData.nickname)
            commit('SET_AVATAR', userData.avatar)
            setToken(true)
            Message.success(response.data.message || '登录成功!')
            resolve(userData)
            
          } else {
            Message.error(response.data.message || '登录失败!请联系系统管理员或重试!')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    LoginByUsername({ commit }, userInfo) {
      // 去空格
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        // 第一次无参数请求给后端
        sysToken().then((token) => {
          console.log('12121212121212')
          if (token.data.code === 1) {
            // 第二次带参数请求后端
            loginByUsername(username, userInfo.password, userInfo.keeplogin, token.data.data).then(response => {
              if (response.data.code === 1) {

                const userData = response.data.data || {}
                // is_super判断是否为超级用户，location确定为版本还是用户
                const { jurisdiction, is_super, location,power = '', avatar} = userData
                // 修改vuex里的rolesDefult是版本还是用户
                commit('SET_ROLES_DEFULT', [location])
                commit('SET_VERSION', location)
                // 直接设为置cookie版本还是用户
                setVersion(location)
                commit('SET_ROUTER_PATH', { jurisdiction, is_super: is_super === 0 ? 0 : 1 })
                setPath({ jurisdiction, is_super })
                commit('SET_TOKEN', true)
                setName(userData.nickname)
                commit('SET_NAME', userData.nickname)
                commit('SET_AVATAR', userData.avatar)
                setToken(true)

                if(!!power){
                  //直接进入平台
                  const Base64 = require('js-base64').Base64
                  const Cookies = require('js-cookie')
                  commit('SET_AVATAR', avatar)
                  commit('SET_ROLES', [])
                  // commit('SET_ROUTER_PATH', { jurisdiction, is_super: is_super === 0 ? 0 : 1 })
                  Cookies.set('STORE_MENU', power)
                  console.log(JSON.parse(Base64.decode(power)), 'storeMenuBasestoreMenuBasestoreMenuBase')
                  setPath({ jurisdiction, is_super })
                }

                Message.success(response.data.message || '登录成功!')
                resolve(userData)

              } else {
                Message.error(response.data.message || '登录失败!请联系系统管理员或重试!')
              }
            }).catch(error => {
          console.log('error22222222',error);

              reject(error)
            })
          }
        }).catch(error => {
          console.log('error',error);
          reject(error)
        })
      })
    },
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) {
            reject('error')
          }
          const data = response.data

          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }

          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then((response) => {
          if (response.data.code === 1) {
            commit('SET_TOKEN', false)
            commit('SET_ROLES', [])
            removeToken()
            removeName()
            removeAgent()
            removeAvatar()
            removePath()
            removeVersion()
            removeIndependent()
            removeIs_Jurisdiction()
            Message.success(response.data.message || '退出成功~')
            resolve()
          } else {
            Message.success(response.data.message || '退出失败，请重试~')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        Message.success('退出成功~')
        resolve()
      })
    },
    ChangeRoles({ commit, dispatch }, role) {
      console.log('ChangeRoles 1111',role)
      return new Promise(resolve => {
        commit('SET_ROLES', role.roles)
        console.log("commit('SET_ROLES', role)", role)
        dispatch('GenerateRoutes', role)
        resolve()
      })
    }
  }
}

export default user
